﻿using System;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Linq;

namespace BoringTodo
{
    public partial class SettingsForm : Form
    {
        private readonly Settings settings;
        private readonly ScreenShot screenShot;

        public SettingsForm(Settings settings, ScreenShot screenShot)
        {
            InitializeComponent();
            this.settings = settings;
            this.screenShot = screenShot;

            // 设置窗体属性
            this.StartPosition = FormStartPosition.CenterScreen;
            this.TopMost = true;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 初始化控件值
            chkEnableAutoScreenshot.Checked = settings.EnableAutoScreenshot;
            numScreenshotInterval.Value = settings.ScreenshotIntervalMinutes;
            txtPrompt.Text = settings.ExplanationText;
            txtMonthlyPrompt.Text = settings.MonthlyExplanationText;
            
            // 添加截图按钮的事件处理
            btnTakeScreenshot.Click += BtnTakeScreenshot_Click;
            btnOpenScreenshotFolder.Click += BtnOpenScreenshotFolder_Click;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // 保存设置
            settings.EnableAutoScreenshot = chkEnableAutoScreenshot.Checked;
            settings.ScreenshotIntervalMinutes = (int)numScreenshotInterval.Value;
            settings.ExplanationText = txtPrompt.Text;
            settings.MonthlyExplanationText = txtMonthlyPrompt.Text;
            settings.Save();
            
            DialogResult = DialogResult.OK;
            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
        
        private void btnExit_Click(object sender, EventArgs e)
        {
            // 先保存当前设置
            settings.EnableAutoScreenshot = chkEnableAutoScreenshot.Checked;
            settings.ScreenshotIntervalMinutes = (int)numScreenshotInterval.Value;
            settings.ExplanationText = txtPrompt.Text;
            settings.MonthlyExplanationText = txtMonthlyPrompt.Text;
            settings.Save();
            
            // 提示用户确认退出
            DialogResult result = MessageBox.Show(
                "确定要退出程序吗？所有未保存的任务数据将会保存。", 
                "退出确认", 
                MessageBoxButtons.YesNo, 
                MessageBoxIcon.Question);
                
            if (result == DialogResult.Yes)
            {
                try
                {
                    // 获取主窗体
                    Form1 mainForm = Application.OpenForms.OfType<Form1>().FirstOrDefault();
                    if (mainForm != null)
                    {
                        // 调用主窗体的退出方法
                        mainForm.ExitApplication();
                    }
                    else
                    {
                        // 如果找不到主窗体，直接退出
                        Logger.Log("从设置界面退出应用程序（未找到主窗体）", LogLevel.Info);
                        Application.Exit();
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError("退出程序时发生错误", ex);
                    Application.Exit(); // 确保仍然退出
                }
            }
        }
        
        private async void BtnTakeScreenshot_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                await screenShot.CaptureAndSaveAsync();
                MessageBox.Show("截图已保存", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Logger.Log("手动截图已保存", LogLevel.Info);
            }
            catch (Exception ex)
            {
                Logger.LogError("截图失败", ex);
                MessageBox.Show($"截图失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        
        private void BtnOpenScreenshotFolder_Click(object sender, EventArgs e)
        {
            try
            {
                string screenshotFolder = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    Constants.AppDataFolder,
                    Constants.ScreenshotsFolder
                );
                
                // 确保文件夹存在
                if (!Directory.Exists(screenshotFolder))
                {
                    Directory.CreateDirectory(screenshotFolder);
                }
                
                // 使用默认文件浏览器打开文件夹
                Process.Start("explorer.exe", screenshotFolder);
                Logger.Log("打开截图文件夹", LogLevel.Info);
            }
            catch (Exception ex)
            {
                Logger.LogError("打开截图文件夹失败", ex);
                MessageBox.Show($"打开截图文件夹失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void btnDataRecovery_Click(object sender, EventArgs e)
        {
            try
            {
                using (var recoveryForm = new DataRecoveryForm())
                {
                    // 先暂时关闭设置窗口
                    this.Hide();
                    
                    if (recoveryForm.ShowDialog() == DialogResult.OK)
                    {
                        // 获取主窗体
                        Form1 mainForm = Application.OpenForms.OfType<Form1>().FirstOrDefault();
                        if (mainForm != null)
                        {
                            // 如果成功恢复，关闭设置窗口并返回主窗口
                            DialogResult = DialogResult.OK;
                            Close();
                            
                            // 提示用户恢复成功
                            MessageBox.Show("数据恢复成功，应用程序将重新加载数据。", 
                                "恢复完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 在主窗体上重新加载数据
                            mainForm.ReloadAllData();
                        }
                        else
                        {
                            // 如果找不到主窗体，只提示成功
                            MessageBox.Show("数据恢复成功，请重新启动应用程序以应用更改。", 
                                "恢复完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            DialogResult = DialogResult.OK;
                            Close();
                        }
                    }
                    else
                    {
                        // 如果取消恢复，重新显示设置窗口
                        this.Show();
                    }
                }
            }
            catch (Exception ex)
            {
                this.Show(); // 确保设置窗口重新显示
                Logger.LogError("打开数据恢复窗口失败", ex);
                MessageBox.Show($"打开数据恢复窗口时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
